<?php
namespace app\common\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\facade\Env;

class Tool extends Command
{
    protected function configure()
    {
        $this->setName('tool')
            ->addArgument('action', Argument::OPTIONAL, "方法名称")
            ->addOption('dirName', null, Option::VALUE_REQUIRED, '目录地址')
            ->setDescription('工具相关任务');
    }

    protected function execute(Input $input, Output $output)
    {

        $action = $input->getArgument('action');
        if ($action == 'delNovel'){
            $this->delNovel();die;
        }
        if (method_exists($this, $action)) {
            $dirName = $input->hasOption('dirName') ? $input->getOption('dirName') : 'cache';
            $this->$action($dirName);
        }

    }

   

    public function clearCache($dirName)
    {
        $CACHE_PATH = Env::get('runtime_path') . "{$dirName}/";
        if ($this->delete_dir_file($CACHE_PATH)) {
            return json(['code' => 200, 'msg' => 'success', 'data' => []]);
        } else {
            return json(['code' => 0, 'msg' => 'err', 'data' => []]);
        }


    }

    /**
     * 循环删除目录和文件
     * @param string $dir_name
     * @return bool
     */
    private function delete_dir_file($dir_name)
    {
        $result = false;
        if (is_dir($dir_name)) {
            if ($handle = opendir($dir_name)) {
                while (false !== ($item = readdir($handle))) {
                    if ($item != '.' && $item != '..') {
                        if (is_dir($dir_name . DIRECTORY_SEPARATOR . $item)) {
                            $this->delete_dir_file($dir_name . $item);
                        } else {
                            $filePath = $dir_name . DIRECTORY_SEPARATOR . $item;
                            @unlink($filePath);
                        }
                    }
                }
                closedir($handle);
                if (@rmdir($dir_name)) {
                    $result = true;
                }
            }
        }
        return $result;
    }

}
